package cn.net.shuxing.yifu.common.service;

import cn.net.shuxing.yifu.common.bean.*;
import cn.net.shuxing.yifu.common.constant.CodeConst;
import cn.net.shuxing.yifu.common.constant.RegistType;
import cn.net.shuxing.yifu.common.constant.UserState;
import cn.net.shuxing.yifu.common.constant.UserType;
import cn.net.shuxing.yifu.common.dto.BaseDto;
import cn.net.shuxing.yifu.common.util.MD5Util;
import cn.net.shuxing.yifu.common.util.RedisKeyCreator;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import cn.net.shuxing.yifu.common.util.StringUtils;
import redis.clients.jedis.Jedis;

import java.io.UnsupportedEncodingException;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;

@Service
public class ShareholderService extends ShareholderCommonService {

    @Autowired
    private UserService userService;

    @Autowired
    private UserInfoService userInfoService;

    @Autowired
    private UserRealInfoService userRealInfoService;

    @Autowired
    private UserBankCardService userBankCardService;

    @Autowired
    private ShareholderLevelService shareholderLevelService;

    @Autowired
    private UserCapitalService userCapitalService;

    @Autowired
    private UserCapitalHistoryService userCapitalHistoryService;

    @Autowired
    private CoinGrantService coinGrantService;

    @Autowired
    private CashWalletService cashWalletService;

    @Autowired
    private UserRoleService userRoleService;

    @Autowired
    private OpenPriceHistoryService openPriceHistoryService;

    @Autowired
    private ShareholderCoinGrantHistoryService shareholderCoinGrantHistoryService;

    @Transactional
    /** 股东姓名、手机号、证件类型、证件号码、开户银行、开户支行、银行卡号、休眠币数量、股东等级、登录密码   **/
    public BaseDto registShareholder(String userRealName, String phoneNum, Integer cardTypeId, String idCardNum,
                                     String openBank, String openBankBranch, String bankCardNum, BigDecimal sleepCoinCount,
                                     Integer shareholderLevel, String password, Integer coinTypeId) {

        Integer userId;
        String name = userRealName;
        System.out.println("实名认证userRealName"+userRealName);
        System.out.println("实名认证Name"+name);
        BaseDto baseDto = new BaseDto();
        UserInfoBind userInfoBind1 = userInfoBindService.getByPhoneNum(phoneNum);
        /** 身份实名认证 **/
        UserRealInfo userRealInfo = new UserRealInfo();
        userRealInfo.setCardTypeId(cardTypeId);
        userRealInfo.setIdCardNum(idCardNum);
        userRealInfo.setRealName(name);
        if (!userRealInfoService.verifyForBack(idCardNum, name)) {
            baseDto.setCode(CodeConst.ERROR);
            return BaseDto.error("身份实名认证失败");
        }
        /** 银行卡实名认证 **/
        UserBankCard userBankCard = new UserBankCard();
        userBankCard.setBankCardNum(bankCardNum);
        userBankCard.setHolderName(name);
        userBankCard.setOpenBank(openBank);
        userBankCard.setOpenBankBranch(openBankBranch);
        userBankCard.setPhoneNum(phoneNum);
        userBankCard.setIdCardNum(idCardNum);
        if (!userBankCardService.verifyForBack(userBankCard)) {
            return BaseDto.error("银行卡实名认证失败");
        }
//      1、判断手机是否被占用
        if (userInfoBind1 != null) {
//            2、判断该手机是否有股东身份
            if (userRoleService.hasRole(userInfoBind1.getId(), UserType.SHAREHOLDER)) {
                return BaseDto.error("该手机已经注册股东身份");
            } else {
//                3、手机是其他身份，判断用户是否实名过
                UserRealInfo userRealInfoVerify = new UserRealInfo();
                userRealInfoVerify.setIdCardNum(idCardNum);
                userRealInfoVerify.setVerified(1);
                userRealInfoVerify = userRealInfoService.get(userRealInfoVerify);

                /** 设置用户userId */
                userId = userInfoBind1.getId();
//                4、如果身份证号实名过
                if (userRealInfoVerify != null) {
//                    判断手机号的userid和和身份证的userId是否一致，如果一致则添加股东角色和股东钱包
                    if (userRealInfoVerify.getId().equals(userId)) {
                        /** 完善用户信息，构建UserInfo对象并存入user_info表 **/
                        UserInfo userInfo = new UserInfo();
                        userInfo.setId(userId);
                        /** 默认股东昵称就是真实姓名 **/
                        userInfo.setNickName(name);
                        userInfoService.insert(userInfo);
                        userRoleService.insert(userId, UserType.SHAREHOLDER, UserState.OK);
                    } else {
                        return BaseDto.error("该手机号已被其他身份证实名认证过。");
                    }
                } else {
//                    如果该手机号未被除股东外的其他用户身份实名认证过，则添加股东角色和股东钱包并更改该手机号的密码为股东身份密码
                    /** 完善用户信息，构建UserInfo对象并存入user_info表 **/
                    UserInfo userInfo = new UserInfo();
                    userInfo.setId(userId);
                    /** 默认股东昵称就是真实姓名 **/
                    userInfo.setNickName(name);
                    if (userInfoService.update(userInfo) < 1) {
//                        当用户昵称未被设置，则使用更新
                        userInfoService.insert(userInfo);
                    }

//                    /** 初始化现金钱包 **/
//                    boolean a = userRoleService.hasRole(userId, UserType.MEMBER);
//                    boolean b = userRoleService.hasRole(userId, UserType.BUSINESS);
//                    boolean c = userRoleService.hasRole(userId, UserType.NONE);
//
//                    if (!(a || b || c)) {
//                        cashWalletService.insert(userId, new BigDecimal(0));
//                    }
//
//                    /** 绑定手机号 **/
//                    UserInfoBind userInfoBind = new UserInfoBind();
//                    userInfoBind.setId(userId);
//                    userInfoBind.setPhoneNum(phoneNum);
//                    userInfoBindService.insert(userInfoBind);

                    /** 更新用户密码为股东密码 */
                    if (StringUtils.hasText(password)) {
                        User user = new User();
                        user.setId(userId);
                        System.out.println("更新用户密码为股东密码" + password);
                        user.setPassword(MD5Util.md5(password));
                        userService.update(user);
//                        userRoleService.insert(userId,UserType.SHAREHOLDER,UserState.OK);
                    }
                }
            }
            userInfoBind1.setSPhoneNum(phoneNum);
            userInfoBindService.update(userInfoBind1);
        } else {
//            如果手机未被使用
            UserRealInfo userRealInfoNot = new UserRealInfo();
            userRealInfoNot.setIdCardNum(idCardNum);
            userRealInfoNot = userRealInfoService.get(userRealInfoNot);
            if (userRealInfoNot != null) {
                return BaseDto.error("该身份证已经注册过");
            } else {

                /** 注册股东用户，将用户基本信息保存至user表 **/
                User user = new User();
                user.setUsername(phoneNum);
                user.setPassword(password);
                user.setRegistType(RegistType.PHONE);
                user.setType(UserType.SHAREHOLDER);
                userService.insert(user);
                /** 获取userId **/
                userId = user.getId();

                /** 完善用户信息，构建UserInfo对象并存入user_info表 **/
                UserInfo userInfo = new UserInfo();
                userInfo.setId(userId);
                /** 默认股东昵称就是真实姓名 **/
                userInfo.setNickName(name);
                userInfoService.insert(userInfo);

                /** 股东实名制，构建股东用户真实信息对象UserRealInfo对象，并存入user_real_info表 **/
                userRealInfoNot = new UserRealInfo();
                userRealInfoNot.setId(userId);
                userRealInfoNot.setVerified(2);
                userRealInfoNot.setCardTypeId(cardTypeId);
                try {
                    name = new String(userBankCard.getHolderName().getBytes("ISO-8859-1"), "UTF-8");
//                    name = new String(userBankCard.getHolderName().getBytes("UTF-8"), "ISO-8859-1");
                } catch (UnsupportedEncodingException e) {
                    e.printStackTrace();
                }
                userRealInfoNot.setRealName(name);
                userRealInfoNot.setIdCardNum(idCardNum);
                userRealInfoService.insert(userRealInfoNot);

//                /** 给股东绑定银行卡，构建UserBankCard对象，并存入user_bank_card表中 **/
//                userBankCard.setUserId(userId);
//                userBankCardService.insert(userBankCard);

                /** 初始化现金钱包 **/
                cashWalletService.insert(userId, new BigDecimal(0));

                /** 绑定手机号 **/
                UserInfoBind userInfoBind = new UserInfoBind();
                userInfoBind.setId(userId);
                userInfoBind.setSPhoneNum(phoneNum);
                userInfoBindService.insert(userInfoBind);
            }
        }

        /** 添加角色 **/
        userRoleService.insert(userId, UserType.SHAREHOLDER, UserState.OK);

        /** 初始化股东等级，构建ShareholderLevel对象，并存入shareholder_level表中 **/
        shareholderLevelService.insert(userId, shareholderLevel);

        /** 初始化股东资产，构建UserCapital对象和UserCapitalHistory对象，并存入user_capital和user_capital_history表中 **/
        UserCapital userCapital = new UserCapital();
        userCapital.setUserId(userId);
        userCapital.setAliveCoinCount(new BigDecimal(0));
        userCapital.setSleepCoinCount(sleepCoinCount);
        userCapital.setCoinTypeId(coinTypeId);
        userCapital.setType(UserType.SHAREHOLDER);
        userCapitalService.insert(userCapital);

        UserCapitalHistory userCapitalHistory = new UserCapitalHistory();
        userCapitalHistory.setUserId(userId);
        userCapitalHistory.setAliveCoinCount(new BigDecimal(0));
        userCapitalHistory.setSleepCoinCount(sleepCoinCount);
        userCapitalHistory.setCoinTypeId(coinTypeId);
        userCapitalHistory.setType(UserType.SHAREHOLDER);
        userCapitalHistoryService.insert(userCapitalHistory);

        /** 构建ShareholderCoinGrantHistory对象，并存入表中 **/
        ShareholderCoinGrantHistory shareholderCoinGrantHistory = new ShareholderCoinGrantHistory();
        shareholderCoinGrantHistory.setCoinTypeId(cardTypeId);
        shareholderCoinGrantHistory.setCount(sleepCoinCount);
        shareholderCoinGrantHistory.setUserId(userId);
        shareholderCoinGrantHistory.setLeftCount(new BigDecimal(0));
        shareholderCoinGrantHistory.setType(1);
        BigDecimal openPrice = openPriceHistoryService.getOpenPrice(coinTypeId);
        shareholderCoinGrantHistory.setOldPrice(openPrice);
        shareholderCoinGrantHistoryService.insert(shareholderCoinGrantHistory);
        return BaseDto.ok("注册成功");
    }

    public List<ShareholderCompletedInfo> searchByLevel(Integer low, Integer high) {
        List<ShareholderLevel> shareholderLevels = shareholderLevelService.searchByLevel(low, high);
        List<ShareholderCompletedInfo> shareholderCompletedInfoList = new ArrayList<>(shareholderLevels.size());
        for (ShareholderLevel shareholderLevel : shareholderLevels) {
            shareholderCompletedInfoList.add(createShareholderCompletedInfo(shareholderLevel.getShareholderId()));
        }
        return shareholderCompletedInfoList;
    }

    public List<ShareholderCompletedInfo> searchByLevel(Integer level) {
        List<ShareholderLevel> shareholderLevels = shareholderLevelService.searchByLevel(level);
        List<ShareholderCompletedInfo> shareholderCompletedInfoList = new ArrayList<>(shareholderLevels.size());
        for (ShareholderLevel shareholderLevel : shareholderLevels) {
            shareholderCompletedInfoList.add(createShareholderCompletedInfo(shareholderLevel.getShareholderId()));
        }
        return shareholderCompletedInfoList;
    }


}
